package model.threads;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;

import view.MainFrame;
import view.Mode;
import accounts.*;
import model.*;
import model.environmentConfig.*;


public class Listener extends Thread{
    private CommunicationChannel channel;
    private ListenerServer listenerServer;
    private Long originalComm;
    private int currentPort;
	
	public Listener(CommunicationChannel channel)
	{
		this.channel=channel;
		currentPort=channel.getListenerPortRange()[0];
		originalComm=Calendar.getInstance().getTimeInMillis();
	}
	
	public void run(){
		listenerServer=new ListenerServer(currentPort, ""+channel.getListeningNode());
		listenerServer.start();
		
		while(true){
			if(Calendar.getInstance().getTimeInMillis()-listenerServer.lastConnection()>=CommunicationChannel.TIME_OUT){
				if(channel.getState()!=ChannelState.NOT_WORKING){
					channel.setState(ChannelState.NOT_WORKING);
					MainFrame.refresh();
				}
			}
			else if(listenerServer.lastConnection()>originalComm && channel.getState()!=ChannelState.WORKING){
				channel.setState(ChannelState.WORKING);
				MainFrame.refresh();
			}
			
			if(!listenerServer.isAlive()){
				listenerServer=new ListenerServer(getNextPort(), ""+channel.getListeningNode());
				listenerServer.start();
			}
		}
	}
	
	private int getNextPort(){
		int var=currentPort;
		
		if(++currentPort>channel.getListenerPortRange()[1]){
			currentPort=channel.getListenerPortRange()[0];
		}
		
		return(var);
	}


	  public void end()
	  {
	    if(listenerServer.isAlive()){
	    	listenerServer.interrupt();
	    }
	  }
}
